import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

class SeventhPage extends StatefulWidget {
  @override
  _SeventhPageState createState() => _SeventhPageState();
}

class _SeventhPageState extends State<SeventhPage> {
  List<Member> _members = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton:
          FloatingActionButton(child: Icon(Icons.refresh), onPressed: () {}),
      appBar: AppBar(
        title: Text('Material App Bar'),
      ),
      body: RefreshIndicator(
        onRefresh: () async {
          print('刷新');
          setState(() {
            _members.clear();
          });

          final url = "https://h5.48.cn/resource/jsonp/allmembers.php?gid=10";
          final res = await http.get(Uri.parse(url));
          if (res.statusCode != 200) {
            throw ("error");
          }
          final json = convert.jsonDecode(res.body);
          final members = json["rows"].map<Member>((rows) {
            return Member(
              id: rows["sid"],
              name: rows["sname"],
              team: rows["tname"],
              pinyin: rows["pinyin"],
              abbr: rows["abbr"],
              tid: rows["tid"],
              pid: rows["pid"],
              pName: rows["pname"],
              nickname: rows["nickname"],
              company: rows["company"],
              joinDay: rows["join_day"],
              height: rows["height"],
              birthDay: rows["birth_day"],
              starSign12: rows["star_sign_12"],
              starSign48: rows["star_sign_48"],
              birthPlace: rows["birth_place"],
              speciality: rows["speciality"],
              hobby: rows["hobby"],
            );
          });

          setState(() => _members = members.toList());
          // members.forEach((v) => print(v));
        },
        child: Scrollbar(
          child: CustomScrollView(
            slivers: [
              SliverToBoxAdapter(),
              SliverPersistentHeader(
                delegate: _MyDelegate("SII", Color(0Xff91cdeb)),
                pinned: true,
              ),
              _buildTeamList("SII"),
              SliverPersistentHeader(
                delegate: _MyDelegate("NII", Color(0Xffae86bb)),
                pinned: true,
              ),
              _buildTeamList("NII"),
              SliverPersistentHeader(
                delegate: _MyDelegate("HII", Color(0Xfff39800)),
                pinned: true,
              ),
              _buildTeamList("HII"),
              SliverPersistentHeader(
                delegate: _MyDelegate("X", Color(0Xffa9cc29)),
                pinned: true,
              ),
              _buildTeamList("X"),   SliverPersistentHeader(
                delegate: _MyDelegate("预备生", Color(0Xff9c129)),
                pinned: true,
              ),
              _buildTeamList("预备生"),
          SliverToBoxAdapter(child: Container(height: 2000,),)
            ],
          ),
        ),
      ),
    );
  }

  SliverGrid _buildTeamList(String teamName) {
    final teamMembers = _members.where((m) => m.team == teamName).toList();

    return SliverGrid(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          final m = teamMembers[index];
          return GestureDetector(
            child: InkWell(
              onTap: () => Navigator.of(context).push(MaterialPageRoute(
                  builder: (_) => DetailPage(
                        member: m,
                      ))),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Hero(

                    tag: m.avatarUrl,
                    child: ClipOval(
                      child: CircleAvatar(
                          backgroundColor: Colors.white,
                          radius: 24,
                          child: Image.network(m.avatarUrl)),
                    ),
                  ),
                  Text(m.name)
                ],
              ),
            ),
          );
        },
        childCount: teamMembers.length,
      ),
      gridDelegate:
          SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 120),
    );
  }
}

class Member {
  final String pinyin;
  final String abbr;
  final String tid;
  final String pid;
  final String pName;
  final String nickname;
  final String company;
  final String joinDay;
  final String height;
  final String birthDay;
  final String starSign12;
  final String starSign48;
  final String birthPlace;
  final String speciality;
  final String hobby;
  final String id;
  final String name;
  final String team;

  Member({
    required this.pinyin,
    required this.abbr,
    required this.tid,
    required this.pid,
    required this.pName,
    required this.nickname,
    required this.company,
    required this.joinDay,
    required this.height,
    required this.birthDay,
    required this.starSign12,

    required this.starSign48,
    required this.birthPlace,
    required this.speciality,
    required this.hobby,
    required this.team,
    required this.id,
    required this.name,

  });

  String get avatarUrl => "https://www.snh48.com/images/member/zp_$id.jpg";

  @override
  String toString() => "$id:$name";
}

class _MyDelegate extends SliverPersistentHeaderDelegate {
  final title;
  Color color;

  _MyDelegate(this.title, this.color);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
        height: 50,
        color: color,
        child: FittedBox(
            child: Text(
          'Team $title',
          style: TextStyle(color: Colors.white),
        )));
  }

  @override
  double get maxExtent => 32;

  @override
  double get minExtent => 32;

  @override
  bool shouldRebuild(covariant _MyDelegate oldDelegate) {
    return oldDelegate.title != title;
  }
}

class DetailPage extends StatelessWidget {
  final Member member;

  const DetailPage({Key? key, required this.member}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(stretch: true,
pinned: true,
            leading: BackButton(

              color: Colors.black,
            ),
            backgroundColor: Colors.pink[100],
            expandedHeight: 300,
            flexibleSpace: FlexibleSpaceBar(
              collapseMode: CollapseMode.pin,
              background: Stack(children: [
                Column(
                  children: [
                    Expanded(
                      child: Image.network(
                          "https://img0.baidu.com/it/u=2093360233,1699744549&fm=26&fmt=auto",
                          fit: BoxFit.cover),
                    ),
                    Container(
                      height: 1,
                      color: Colors.pink[200],
                    ),
                    Expanded(child: SizedBox())
                  ],
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                ),
                Center(
                  child: Padding(
                    padding: const EdgeInsets.all(100.0),
                    child: AspectRatio(
                      aspectRatio: 1,
                      child: Hero(
                        tag: member.avatarUrl,
                        child: ClipOval(
                          child: Image.network(
                            member.avatarUrl,
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    ),
                  ),
                )
              ]),
              title: Text(
              "  SNH-48 ${member.name}",
                style: TextStyle(color: Colors.white),
              ),
            ),
          ),
          SliverList(
              delegate: SliverChildListDelegate([
            _buildInfo("拼音", member.pinyin),
            _buildInfo("期属", member.pName),
            _buildInfo("昵称", member.nickname),
            _buildInfo("加入日期", member.joinDay),
            _buildInfo("身高", '${member.height}cm'),
            _buildInfo("生日", member.birthDay),
            _buildInfo("星座", member.starSign12),
            _buildInfo("出生地", member.birthPlace),
            _buildInfo("特长", member.speciality),
            _buildInfo("兴趣爱好", member.hobby),
          ]))
        ],
      ),
    );
  }

  _buildInfo(String title, String content) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(title),
            Text(content),
          ],
        ),
      ),
    );
  }
}
